<!-- 知识点学习页面 - 支持分类浏览和卡片展示 -->
<template>
	<view class="java-learn-container" :style="containerStyle">
		<!-- 页面头部 -->
		<view class="page-header" :style="{ paddingTop: safeDistance + 'px' }">
			<view class="header-row">
				<view class="back-button" @click="handleGoBack">
					<text class="back-icon">←</text>
				</view>
				<view class="header-content">
					<text class="header-title">{{ getPageTitle }}</text>
					<text class="header-subtitle">{{ getPageSubtitle }}</text>
				</view>
			</view>
		</view>

		<!-- 主要内容区域 -->
		<view class="content-wrapper">
			<!-- 分类选择器 -->
			<view class="category-selector-wrapper">
				<view class="category-selector-header">
					<text class="category-title">📚 知识分类</text>
					<text class="card-count">{{ currentCategoryCards.length }} 个知识点</text>
				</view>
				<scroll-view class="category-selector" scroll-x show-scrollbar="false" :scroll-into-view="scrollIntoView">
					<view v-for="(category, index) in categories" :key="category.id" :id="'category-' + index"
						class="category-item" :class="{ active: currentSwiperIndex === index }"
						@click="handleCategoryClick(index)">
						<text class="category-icon">{{ category.icon }}</text>
						<text class="category-text">{{ category.name }}</text>
					</view>
				</scroll-view>
			</view>

			<!-- 内容区域 - Swiper分页展示 -->
			<swiper class="content-swiper" :current="currentSwiperIndex" @change="handleSwiperChange" :duration="300">
				<swiper-item v-for="category in categories" :key="category.id" class="swiper-page">
					<scroll-view class="card-container" scroll-y show-scrollbar="false">
						<!-- 加载状态 -->
						<view v-if="isCategoryLoading(category.code)" class="loading-state">
							<text class="loading-icon">⏳</text>
							<text class="loading-text">加载中...</text>
						</view>

						<!-- 空状态 -->
						<view v-else-if="getCategoryCards(category.code).length === 0" class="empty-state">
							<text class="empty-icon">📖</text>
							<text class="empty-title">暂无知识点</text>
							<text class="empty-desc">{{ getEmptyDescription }}</text>
						</view>

						<!-- 知识卡片网格 -->
						<view v-else class="cards-grid">
							<view v-for="(card, index) in getCategoryCards(category.code)" :key="card.id"
								class="grid-card" @click="handleLearnMore(card)">
								<view class="grid-card-content">
									<view class="grid-card-title-row">
										<view class="grid-card-number">
											<text class="number-text">{{ index + 1 }}</text>
										</view>
										<text class="grid-card-title">{{ card.title }}</text>
									</view>
									<text class="grid-card-desc">{{ card.description }}</text>
									<view class="grid-card-footer">
										<view class="grid-card-badge" :style="{ background: card.difficultyBg }">
											<text class="badge-text">{{ card.difficulty }}</text>
										</view>
										<view class="grid-card-points">
											<text class="points-icon">💡</text>
											<text class="points-text">{{ card.keyPointsFinal.length }}个要点</text>
										</view>
									</view>
								</view>
							</view>
						</view>
					</scroll-view>
				</swiper-item>
			</swiper>
		</view>

		<!-- AI助手按钮 -->
		<AiChatButton buttonText="AI助手" />
	</view>
</template>


<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import AiChatButton from '@/components/AiChatButton.vue';
import { getCategoriesByTechCodeAPI } from '@/services/categories';
import { getKnowledgeCardsByTechAndCategoryAPI } from '@/services/knowledge-cards';
import { getTechnologyByCodeAPI } from '@/services/technologies';
import { getThemeStyles } from '@/stores/theme';
import { parseKnowledgeCard } from '@/utils/knowledge';
import type { KnowledgeDetail, Category, Technology } from '@/types';

// 核心数据
const techCode = ref<string>('java'); // 当前技术栈代码
const currentTech = ref<Technology | null>(null); // 技术栈信息
const loading = ref(true); // 全局加载状态
const categories = ref<Category[]>([]); // 知识分类列表

// 知识数据存储
const knowledgeCardsData = ref<Map<string, KnowledgeDetail[]>>(new Map()); // 所有分类的知识卡片数据
const loadingStates = ref<Map<string, boolean>>(new Map()); // 各分类的加载状态

// UI状态
const currentSwiperIndex = ref(0); // 当前Swiper索引
const scrollIntoView = ref(''); // 分类滚动定位

// 样式计算
const themeStyles = computed(() => getThemeStyles());
const containerStyle = computed(() => ({ backgroundColor: themeStyles.value.bgPrimary }));
const safeDistance = computed(() => (uni.getSystemInfoSync().safeAreaInsets?.top || 0) + 20); // 安全区域适配

// 页面内容计算
const getPageTitle = computed(() => {
	if (currentTech.value) {
		return `${currentTech.value.icon} ${currentTech.value.name}核心知识点`;
	}
	return '知识点学习';
});

const getPageSubtitle = computed(() => {
	if (currentTech.value) {
		return `每张卡片聚焦一个${currentTech.value.name}核心概念`;
	}
	return '探索技术知识';
});

const getEmptyDescription = computed(() => {
	if (currentTech.value) {
		return `敬请期待更多${currentTech.value.name}知识点卡片`;
	}
	return '敬请期待更多知识点卡片';
});

// 当前分类的卡片数据
const currentCategoryCards = computed(() => {
	const currentCategory = categories.value[currentSwiperIndex.value];
	return currentCategory ? (knowledgeCardsData.value.get(currentCategory.code) || []) : [];
});

// 生命周期
onLoad((options: any) => {
	if (options.techCode) {
		techCode.value = options.techCode as string;
	}
});

onMounted(async () => {
	await loadKnowledgeData();
});

// 页面离开时清除缓存
onUnmounted(() => {
	clearCache();
});

// 数据加载方法
const loadTechnologyInfo = async () => {
	try {
		const res = await getTechnologyByCodeAPI(techCode.value);
		currentTech.value = res.data || null;
	} catch (error) {
		console.error('加载技术栈信息失败:', error);
		currentTech.value = null;
	}
};

const loadCategoriesData = async () => {
	try {
		const res = await getCategoriesByTechCodeAPI(techCode.value);
		categories.value = res.data || [];
	} catch (error) {
		console.error('加载分类失败:', error);
		categories.value = [];
	}
};

// 加载指定分类的知识卡片数据（懒加载）
const loadCategoryKnowledgeCards = async (categoryCode: string) => {
	// 如果已经加载过或正在加载，则跳过
	if (knowledgeCardsData.value.has(categoryCode) || loadingStates.value.get(categoryCode)) {
		return;
	}

	try {
		// 设置加载状态
		loadingStates.value.set(categoryCode, true);
		
		const res = await getKnowledgeCardsByTechAndCategoryAPI(techCode.value, categoryCode);
		const cards = res.data || [];
		const parsedCards = cards.map((card: any) => parseKnowledgeCard(card));
		knowledgeCardsData.value.set(categoryCode, parsedCards);
	} catch (error) {
		console.error(`加载分类 ${categoryCode} 失败:`, error);
		knowledgeCardsData.value.set(categoryCode, []); // 设置空数组
	} finally {
		// 清除加载状态
		loadingStates.value.set(categoryCode, false);
	}
};

// 加载第一个分类的知识卡片数据
const loadFirstCategoryCards = async () => {
	if (categories.value.length > 0) {
		await loadCategoryKnowledgeCards(categories.value[0].code);
	}
};

// 主数据加载入口
const loadKnowledgeData = async () => {
	uni.showLoading({
		title: '加载中...',
		mask: true
	});
	try {
		// 先加载技术栈信息和分类数据
		await Promise.all([loadTechnologyInfo(), loadCategoriesData()]);
		// 然后只加载第一个分类的知识卡片数据
		await loadFirstCategoryCards();
	} catch (error) {
		console.error('加载知识点数据失败:', error);
		uni.showToast({
			title: '加载失败，请重试',
			icon: 'none',
			duration: 2000
		});
	} finally {
		uni.hideLoading();
		loading.value = false;
	}
};

// 工具方法
const getCategoryCards = (categoryCode: string): KnowledgeDetail[] => {
	return knowledgeCardsData.value.get(categoryCode) || [];
};

const isCategoryLoading = (categoryCode: string): boolean => {
	return loadingStates.value.get(categoryCode) || false; // 使用分类特定的加载状态
};

// 清除缓存
const clearCache = () => {
	knowledgeCardsData.value.clear();
	loadingStates.value.clear();
};

// 事件处理
const handleCategoryClick = async (index: number) => {
	currentSwiperIndex.value = index;
	scrollIntoView.value = `category-${index}`; // 滚动到对应分类
	
	// 懒加载当前分类的知识卡片数据
	const category = categories.value[index];
	if (category) {
		await loadCategoryKnowledgeCards(category.code);
	}
};

const handleSwiperChange = async (e: any) => {
	currentSwiperIndex.value = e.detail.current;
	scrollIntoView.value = `category-${e.detail.current}`;
	
	// 懒加载当前分类的知识卡片数据
	const category = categories.value[e.detail.current];
	if (category) {
		await loadCategoryKnowledgeCards(category.code);
	}
};

const handleLearnMore = (card: KnowledgeDetail) => {
	// 跳转到详情页面，传递知识卡片ID和技术栈代码
	uni.navigateTo({
		url: `/pages/technologies/knowledge/detail?cardId=${card.id}&techCode=${techCode.value}`
	});
};

const handleGoBack = () => {
	uni.navigateBack();
};
</script>

<style lang="scss" scoped>
.java-learn-container {
	height: 100vh;
	display: flex;
	flex-direction: column;
	overflow: hidden;
	position: relative;
	transition: background 0.5s ease;
}

.page-header {
	flex-shrink: 0;
	padding: 20rpx 40rpx 40rpx;
	background: v-bind('themeStyles.bgPrimary');
	position: relative;
	z-index: 10;
}

.header-row {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.back-button {
	width: 72rpx;
	height: 72rpx;
	background: v-bind('themeStyles.bgCard');
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: v-bind('themeStyles.cardShadow');
	transition: all 0.3s ease;
	flex-shrink: 0;

	&:active {
		transform: scale(0.92);
		box-shadow: v-bind('themeStyles.hoverShadow');
	}
}

.back-icon {
	font-size: 44rpx;
	color: v-bind('themeStyles.textPrimary');
	font-weight: 700;
}

.header-content {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 16rpx;
}

.header-title {
	font-size: 40rpx;
	font-weight: 800;
	letter-spacing: 1rpx;
	line-height: 1.3;
	color: v-bind('themeStyles.textPrimary');
}

.header-subtitle {
	font-size: 24rpx;
	opacity: 0.9;
	font-weight: 500;
	line-height: 1.4;
	color: v-bind('themeStyles.textSecondary');
}

.content-wrapper {
	flex: 1;
	display: flex;
	flex-direction: column;
	padding: 0 20rpx;
	overflow: hidden;
	position: relative;
	z-index: 1;
}

.category-selector-wrapper {
	flex-shrink: 0;
	margin-bottom: 20rpx;
	padding: 32rpx 24rpx 28rpx;
	background: v-bind('themeStyles.bgCard');
	border-radius: 32rpx;
	box-shadow: v-bind('themeStyles.cardShadow');
}

.category-selector-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 24rpx;
}

.category-title {
	font-size: 32rpx;
	font-weight: 700;
	color: v-bind('themeStyles.textPrimary');
}

.card-count {
	font-size: 24rpx;
	color: white;
	padding: 8rpx 16rpx;
	background: v-bind('themeStyles.primaryGradient');
	border-radius: 100rpx;
	font-weight: 600;
	box-shadow: v-bind('themeStyles.buttonShadow');
}

.category-selector {
	display: flex;
	gap: 16rpx;
	white-space: nowrap;
}

.category-item {
		display: inline-flex;
		flex-direction: column;
		align-items: center;
		gap: 8rpx;
		padding: 24rpx 28rpx;
		background: v-bind('themeStyles.bgSecondary');
		color: v-bind('themeStyles.textSecondary');
		border: 3rpx solid v-bind('themeStyles.borderColor');
		border-radius: 24rpx;
		margin-right: 10px;
		font-size: 24rpx;
		font-weight: 600;
		transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
		box-shadow: v-bind('themeStyles.cardShadow');
		flex-shrink: 0;
		min-height: 120rpx;
		justify-content: center;
		min-width: 180rpx;
		width: 180rpx;

	&:active {
		transform: translateY(-4rpx) scale(0.97);
	}
}

.category-icon {
	font-size: 40rpx;
	transition: transform 0.4s ease;
}

.category-text {
	font-size: 24rpx;
	font-weight: 600;
	white-space: nowrap;
}

.category-item.active {
	color: white;
	background: v-bind('themeStyles.primaryGradient');
	border: 4rpx solid rgba(255, 255, 255, 0.8);
	box-shadow: v-bind('themeStyles.buttonShadow'), 0 0 0 1rpx rgba(255, 255, 255, 0.5);
	transform: translateY(-4rpx);

	.category-icon {
		transform: scale(1.15) rotate(5deg);
	}
}

.content-swiper {
	flex: 1;
	width: 100%;
	height: 100%;
}

.swiper-page {
	width: 100%;
	height: 100%;
}

.card-container {
	width: 100%;
	height: 100%;
}

.cards-grid {
	display: grid;
	grid-template-columns: repeat(2, 1fr);
	gap: 32rpx 20rpx;
	padding: 20rpx;
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 120rpx 40rpx;
	gap: 24rpx;
	background: v-bind('themeStyles.bgCard');
	border-radius: 32rpx;
	box-shadow: v-bind('themeStyles.cardShadow');
	min-height: 400rpx;
}

.loading-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 120rpx 40rpx;
	gap: 24rpx;
	background: v-bind('themeStyles.bgCard');
	border-radius: 32rpx;
	box-shadow: v-bind('themeStyles.cardShadow');
	min-height: 400rpx;
}

.loading-icon {
	font-size: 80rpx;
	animation: loadingRotate 1s linear infinite;
}

.loading-text {
	font-size: 28rpx;
	color: v-bind('themeStyles.textSecondary');
	font-weight: 500;
}

@keyframes loadingRotate {
	from { transform: rotate(0deg); }
	to { transform: rotate(360deg); }
}

.empty-icon {
	font-size: 80rpx;
	opacity: 0.6;
}

.empty-title {
	font-size: 32rpx;
	font-weight: 700;
	color: v-bind('themeStyles.textPrimary');
}

.empty-desc {
	font-size: 26rpx;
	color: v-bind('themeStyles.textSecondary');
	text-align: center;
	line-height: 1.6;
	opacity: 0.8;
}

.grid-card {
	background: v-bind('themeStyles.bgCard');
	border-radius: 24rpx;
	padding: 24rpx;
	box-shadow: v-bind('themeStyles.cardShadow');
	border: 2rpx solid v-bind('themeStyles.borderColor');
	transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
	position: relative;
	overflow: hidden;
	display: flex;
	flex-direction: column;
	min-height: 280rpx;
	&:active {
		transform: scale(0.96) translateY(-4rpx);
		box-shadow: v-bind('themeStyles.hoverShadow');
		border-color: v-bind('themeStyles.primaryColor');
	}
}

.grid-card-number {
		width: 48rpx;
		height: 48rpx;
		background: v-bind('themeStyles.primaryGradient');
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: v-bind('themeStyles.buttonShadow');
		margin-right: 16rpx;
	}
	
	.grid-card-title-row {
		display: flex;
		align-items: center;
		margin-bottom: 16rpx;
	}

.number-text {
	font-size: 24rpx;
	font-weight: 900;
	color: white;
}

.grid-card-content {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 0;
	}

.grid-card-title {
	font-size: 28rpx;
	font-weight: 700;
	color: v-bind('themeStyles.textPrimary');
	line-height: 1.4;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 2;
	line-clamp: 2;
	overflow: hidden;
	text-overflow: ellipsis;
}

.grid-card-desc {
	flex: 1;
	font-size: 24rpx;
	color: v-bind('themeStyles.textSecondary');
	line-height: 1.5;
	display: -webkit-box;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 3;
	line-clamp: 3;
	overflow: hidden;
	text-overflow: ellipsis;
	opacity: 0.9;
}

.grid-card-footer {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-top: auto;
	padding-top: 16rpx;
}

.grid-card-badge {
	padding: 6rpx 16rpx;
	border-radius: 100rpx;
	font-size: 20rpx;
	font-weight: 600;
	color: white;
	text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.2);
}

.badge-text {
	font-size: 20rpx;
	font-weight: 600;
}

.grid-card-points {
	display: flex;
	align-items: center;
	gap: 8rpx;
}

.points-icon {
	font-size: 24rpx;
}

.points-text {
	font-size: 22rpx;
	color: v-bind('themeStyles.textSecondary');
	font-weight: 500;
	opacity: 0.8;
}

</style>